package com.atguigu.gmall.product.controller;


import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.config.FastDFSClientUtil;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author mqx
 * @date 2021-4-12 15:15:09
 */
@RestController
@RequestMapping("admin/product")
public class FileUploadController {
    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    //获取fast_dfs.properties文件中的fileServerUrl的值
    @Value("${fileServerUrl}")
    private String fileServerUrl;

    /**
     * 上传文件   浏览器上传文件  (springmvc上传文件)->  controller
     * @param file  file:上传文件的名称
     * @return
     */
    @PostMapping("/fileUpload")
    public Result uploadFile(MultipartFile file){
        try {
            if (file == null){
                throw new RuntimeException("文件不存在");
            }

            //返回值 ：图片在存储服务器的位置  group1/M00/02/44/xxjdlsdjls
            String filepath = fastDFSClientUtil.uploadFile(file);
            System.out.println("图片在存储服务器的位置: "+filepath);
            //想要的地址 ： http://192.168.200.130/group1/M00/02/44/xxjdlsdjls
            return Result.ok(fileServerUrl+filepath);
        } catch (IOException e) {
            e.printStackTrace();
        }
       return Result.ok();
    }

    /**
     * 从fastdfs文件系统中删除图片
     * @param filePath  group1/M00/02/44/xxjdlsdjls
     * @return
     */
    @GetMapping("/del")
    public String delFile(String filePath){
        try {
            fastDFSClientUtil.delFile(filePath);
            return "删除成功";
        }catch (Exception e){
            e.printStackTrace();
        }
        return "删除失败";
    }
}
